package android.slc.extras.component.attchment.domain;


import android.slc.appbase.R;
import android.slc.appbase.api.slc.callback.SlcObserver;
import android.slc.appbase.api.slc.callback.po.SlcEntity;
import android.slc.appbase.api.slc.config.ApiConfig;
import android.slc.appbase.ui.utils.LoadingUtils;
import android.slc.attachment.bean.Progress;
import android.slc.commonlibrary.util.compat.SlcIntentUtils;
import android.slc.extras.component.attchment.entity.Attachment;
import android.slc.extras.component.attchment.repository.remote.AttachmentServiceRepository;
import android.slc.extras.component.attchment.utils.AttachmentUtils;
import android.slc.mp.po.BaseItem;
import android.slc.mp.po.FileItem;
import android.slc.network.SimpleDownloadByOk;
import android.slc.network.SimpleDownloadByOkListener;
import android.slc.rx.SimpleObserver;
import android.slc.rx.SlcRxJavaUtils;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ArrayUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.File;
import java.util.Collections;
import java.util.List;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * @Description:
 * @Author: sunlunchang
 * @CreateDate: 2021/09/15 上午 10:50
 */
public class DefaultAttachmentAdapter implements AttachmentReviewVmBox.AttachmentAdapter {
    protected AttachmentReviewVmBox<? extends AttachmentReviewVmBox.AttachmentAdapter> attachmentReviewVmBox;

    @Override
    public void setAttachmentReviewVmBox(AttachmentReviewVmBox<? extends AttachmentReviewVmBox.AttachmentAdapter> attachmentVmBox) {
        this.attachmentReviewVmBox = attachmentVmBox;
    }

    @Override
    public void onPreview(Attachment attachment) {
        ActivityUtils.startActivity(SlcIntentUtils.getOpenAndroidFileIntent(attachment.isLocalBody() ? attachment.getLocalPath() : attachment.getNetPath()));
    }

    @Override
    public void onDownload(Attachment attachment) {
        SimpleDownloadByOk.newBuilder(attachment.getNetPath(), PathUtils.getExternalAppDownloadPath(), attachment.getNetBody().getNetBodyName())
                .setHeaderMapFields(SimpleDownloadByOk.createHeadBuilder()
                        .add(ApiConfig.Key.KEY_TOKEN, ApiConfig.getInstance().getToken())
                        .build())
                .toCommonlyConfig()
                .build()
                .getDownloadTask().enqueue(new SimpleDownloadByOkListener() {
            @Override
            protected void started(@NonNull com.liulishuo.okdownload.DownloadTask task) {
                Progress progressTemp = new Progress();
                progressTemp.status = Progress.WAITING;
                attachment.setProgress(progressTemp);
                notifyAttItemDataChange(attachment);
            }

            @Override
            protected void progress(@NonNull com.liulishuo.okdownload.DownloadTask task, int percentage, long currentOffset, long totalLength) {
                Progress progressTemp = new Progress();
                progressTemp.status = Progress.LOADING;
                progressTemp.totalSize = totalLength == 0 ? -1 : totalLength;
                progressTemp.fraction = percentage;
                progressTemp.currentSize = currentOffset;
                if (progressTemp.totalSize == -1) {
                    progressTemp.fraction = 50;
                }
                attachment.setProgress(progressTemp);
                notifyAttItemDataChange(attachment);
            }

            @Override
            protected void completed(@NonNull com.liulishuo.okdownload.DownloadTask task) {
                //下载完成
                Progress progressTemp = new Progress();
                progressTemp.status = Progress.FINISH;
                progressTemp.fraction = 100;
                attachment.setProgress(progressTemp);
                notifyAttItemDataChange(attachment);
                //设置netBody

                File file = FileUtils.getFileByPath(task.getFile().getAbsolutePath());
                if (file != null) {
                    BaseItem baseItem = new FileItem();
                    baseItem.setSize(file.length());
                    baseItem.setExtension(FileUtils.getFileExtension(file));
                    baseItem.setDisplayName(file.getName());
                    baseItem.setPath(file.getPath());
                    baseItem.setModified(FileUtils.getFileLastModified(file));
                    baseItem.setMediaTypeTag(AttachmentUtils.expandName2MediaType(baseItem.getExtension()));
                    attachment.setLocalBody(baseItem);
                    notifyAttItemDataChange(attachment);
                }
                ActivityUtils.startActivity(SlcIntentUtils.getOpenAndroidFileIntent(task.getFile().getAbsolutePath()));
            }

            @Override
            protected void error(@NonNull com.liulishuo.okdownload.DownloadTask task, @NonNull Exception e) {
                Progress progressTemp = new Progress();
                progressTemp.status = Progress.ERROR;
                attachment.setProgress(progressTemp);
                notifyAttItemDataChange(attachment);
                task.cancel();
            }

        });
    }

    /**
     * 通知更改
     *
     * @param attachment
     */
    private void notifyAttItemDataChange(Attachment attachment) {
        if (attachmentReviewVmBox != null) {
            attachmentReviewVmBox.notifyAttItemDataChangeLd.setValue(attachment);
        }
    }

    @Override
    public void onRefresh(SlcObserver<List<Attachment>> observer) {
        if (attachmentReviewVmBox != null) {
            if (!ArrayUtils.isEmpty(attachmentReviewVmBox.ids)) {
                AttachmentServiceRepository.getAttachmentByIds(attachmentReviewVmBox.ids)
                        .to(attachmentReviewVmBox.bindToLifecycle())
                        .subscribe(observer);
            } else if (CollectionUtils.isNotEmpty(attachmentReviewVmBox.getStorageFormList())) {
                Observable.just(attachmentReviewVmBox.getStorageFormList()).map(storageFormList ->
                        SlcEntity.getSlcEntityByData(AttachmentServiceRepository.storageFormListToAttachment(attachmentReviewVmBox.getStorageFormList())))
                        .compose(SlcRxJavaUtils.applyOoAndroidSchedulers())
                        .to(attachmentReviewVmBox.bindToLifecycle())
                        .subscribe(observer);
            }
        }
    }

    @Override
    public void uploadAttachmentSingleDirectlyUnder(Attachment attachment) {
        uploadAttachmentSingle(attachment)
                .map(attachment1 -> {
                    notifyAttItemDataChange(attachment1);
                    return attachment1;
                })
                .subscribe(new SimpleObserver<Attachment>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        super.onSubscribe(d);
                        LoadingUtils.showLoadingDialog(String.valueOf(DefaultAttachmentAdapter.this.hashCode()), R.string.label_file_are_uploading);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        ToastUtils.showShort(R.string.label_file_upload_failed);
                        LoadingUtils.dismissLoadingDialog(String.valueOf(DefaultAttachmentAdapter.this.hashCode()));
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        ToastUtils.showShort(R.string.label_file_uploaded_success);
                        LoadingUtils.dismissLoadingDialog(String.valueOf(DefaultAttachmentAdapter.this.hashCode()));
                    }
                });
    }

    @Override
    public Observable<Attachment> uploadAttachmentSingle(Attachment attachment) {
        return uploadAttachment(Collections.singletonList(attachment));
    }

    @Override
    public Observable<Attachment> uploadAttachment() {
        return uploadAttachment(attachmentReviewVmBox.getDataList());
    }

    private Observable<Attachment> uploadAttachment(List<Attachment> attachmentList) {
        return AttachmentServiceRepository.uploadAttachmentListByFilter(attachmentList).map(attachment -> {
            notifyAttItemDataChange(attachment);
            return attachment;
        });
    }
}
